﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.Model;
using SIG.Model.Enums;
using SIG.Service;
using SIG.ViewModel;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;
using SIG.ViewModel.Admin.FQAs;
using SIG.InputModel.Admin.FQAs;
using SIG.Model.FQAs;
using SIG.Resources.Admin;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class QuestionCategoryController : BaseController
    {
        private readonly IQuestionCategoryService _categoryService;
       
        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public QuestionCategoryController(IQuestionCategoryService categoryService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _categoryService = categoryService;
         
            _pageMetaService = pageMetaService;
            _mapper = mapper;

        }
        // GET: Admin/QuestionCategory

        #region 新闻分类

        public ActionResult Index(int? page, string keyword)
        {
            QuestionCategoryListVM categoryListVM = GetElements(page, keyword);
            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(categoryListVM);           
        }

        private QuestionCategoryListVM GetElements(int? page, string keyword)
        {
            var specialistListVM = new QuestionCategoryListVM();

            specialistListVM.Keyword = keyword;
            specialistListVM.PageIndex = (page ?? 1) - 1;
            specialistListVM.PageSize = SettingsManager.Question.PageSize;
            int totalCount;
            var specialistlist = _categoryService.GetPagedElements(specialistListVM.PageIndex, specialistListVM.PageSize, specialistListVM.Keyword, out totalCount);
            var specialistVMList = _mapper.Map<List<QuestionCategory>, List<QuestionCategoryVM>>(specialistlist);
            specialistListVM.TotalCount = totalCount;
            specialistListVM.Categories = new StaticPagedList<QuestionCategoryVM>(specialistVMList, specialistListVM.PageIndex + 1, specialistListVM.PageSize, specialistListVM.TotalCount); ;
            return specialistListVM;
        }

        [HttpPost]       
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/QuestionSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);               
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        [HttpGet]
        public ActionResult Add()
        {            
            var vCategory = new QuestionCategoryIM();
            vCategory.Active = true;
            vCategory.Importance = 0;
        
            return PartialView("_Add", vCategory);
        }



        [HttpPost]
        public JsonResult Add(QuestionCategoryIM vm)
        {       

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newCategory = _mapper.Map<QuestionCategoryIM, QuestionCategory>(vm);
            _categoryService.Create(newCategory);

           

            int count;
            var pageSize = SettingsManager.Question.PageSize;
            var list = _categoryService.GetPagedElements(0, pageSize, string.Empty, out count);
            List<QuestionCategoryVM> categories = _mapper.Map<List<QuestionCategory>, List<QuestionCategoryVM>>(list);
            AR.Data = RenderPartialViewToString("_CategoryList", categories);

            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.QuestionCategory));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {
          
            QuestionCategory category = _categoryService.GetById(id);        
            if (category == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<QuestionCategoryIM>(category);         
            
            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(QuestionCategoryIM vm)
        {
         
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newCategory = _mapper.Map<QuestionCategoryIM, QuestionCategory>(vm);
            _categoryService.Update(newCategory);

            //var pageMeta = _pageMetaService.GetPageMeta(ModelType.ARTICLECATEGORY, vm.Id);
            //pageMeta = pageMeta ?? new PageMeta();


            //if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            //{

            //    pageMeta.ObjectId = vm.Id;
            //    pageMeta.Keyword = vm.Keywords;
            //    pageMeta.Description = vm.SEODescription;
            //    pageMeta.ModelType = ModelType.ARTICLECATEGORY;

            //    if (pageMeta.Id > 0)
            //    {
            //        _pageMetaService.Update(pageMeta);
            //    }
            //    else
            //    {
            //        _pageMetaService.Create(pageMeta);
            //    }
            //}

            var category = _mapper.Map<QuestionCategoryVM>(newCategory);
            AR.Id = category.Id;
            AR.Data = RenderPartialViewToString("_CategoryItem", category);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.QuestionCategory));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            QuestionCategory vCategory = _categoryService.GetById(id);

            if (vCategory.Questions.Any())
            {
                AR.Setfailure("此分类下面还有文章存在，不能删除！");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _categoryService.Delete(vCategory);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.QuestionCategory));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vCategory = _categoryService.GetById(id);
            if (vCategory == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vCategory.Active = !vCategory.Active;
                _categoryService.Update(vCategory);

                var vm = _mapper.Map<QuestionCategoryVM>(vCategory);

                AR.Data = RenderPartialViewToString("_CategoryItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.QuestionCategory));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }
       
        #endregion
    }
}